<template>
  <div>

    <div class="container">
      <div class="handle-box">
        <el-input v-model="query.title" clearable placeholder="标题" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-input v-model="query.message" clearable placeholder="通知内容" style="width: 200px;" class="handle-input mr10"></el-input>
         <el-cascader
          v-model="query.selected"
          :options="cascaderOptions"
          :props="cascaderProps"
          filterable
          clearable
          placeholder="请选择会议和用户类型"
          class="handle-input mr10"
          style="width: 280px"
          @change="onCascaderChange"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
        <!-- ✅ 导入导出按钮 -->
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <!-- <el-table-column prop="notificationId" label="序号"></el-table-column> -->
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column label="信息" prop="message" width="450px">
          <template slot-scope="scope">
            <div v-html="scope.row.message" style="max-height: 120px; overflow: auto;"></div>
          </template>
        </el-table-column>
        <el-table-column prop="participantTypes.typeName" label="用户类型"></el-table-column>
        <el-table-column prop="conferences.conferenceName" label="目标会议"></el-table-column>
        <el-table-column prop="sentAt" label="发送时间" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.notificationId)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑 -->
    <el-dialog title="编辑通知" :visible.sync="editVisible" width="60%" :close-on-click-modal="false" class="notification-dialog">
      <!-- 滚动容器包裹 form -->
      <div class="dialog-scroll-body">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <!-- 会议与用户类型 -->
          <el-form-item label="会议与用户" prop="cascader">
            <el-cascader
              v-model="form.cascader"
              :options="cascaderOptions"
              :props="cascaderProps"
              filterable
              clearable
              placeholder="请选择会议和用户类型"
              style="width: 100%"
              @change="handleCascaderChange"
            />
          </el-form-item>
        
          <!-- 发送时间 -->
          <el-form-item label="发送时间" prop="sentAt">
            <el-date-picker
              v-model="form.sentAt"
              type="datetime"
              placeholder="选择发送时间"
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        
          <!-- 标题 -->
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
        
          <!-- 富文本信息 -->
            <el-form-item label="信息" prop="message">
              <quill-editor
                v-model="form.message"
                ref="myTextEditor"
                :options="editorOption"
                style="height: 350px"
                @blur="onEditorBlur"
                @change="onEditorChange"
              />
            </el-form-item>
        </el-form>
      </div>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
<el-dialog title="新增通知" :visible.sync="addVisible" width="60%" :close-on-click-modal="false" class="notification-dialog">
  <!-- 滚动容器包裹 form -->
  <div class="dialog-scroll-body">
    <el-form
      ref="formRef"
      :model="addForm"
      :rules="rules"
      label-width="100px"
    >
             <!-- 会议与用户类型 -->
       <el-form-item label="会议与用户" prop="cascader">
         <el-cascader
           v-model="addForm.cascader"
           :options="cascaderOptions"
           :props="cascaderPropsMultiple"
           filterable
           clearable
           multiple
           collapse-tags
           placeholder="请选择会议和用户类型（支持多选）"
           style="width: 100%"
           @change="handleCascaderChangeAdd"
         />
       </el-form-item>

       <!-- 显示已选择的目标 -->
       <el-form-item label="已选择" v-if="addForm.selectedTargets.length > 0">
         <div class="selected-targets">
           <el-tag 
             v-for="(target, index) in addForm.selectedTargets" 
             :key="index" 
             type="info" 
             size="small"
             style="margin-right: 8px; margin-bottom: 4px;"
           >
             {{ getTargetDisplayName(target) }}
           </el-tag>
           <div class="target-count">
             <small>共选择了 {{ addForm.selectedTargets.length }} 个目标</small>
           </div>
         </div>
       </el-form-item>

      <!-- 发送时间 -->
      <el-form-item label="发送时间" prop="sentAt">
        <el-date-picker
          v-model="addForm.sentAt"
          type="datetime"
          placeholder="选择发送时间"
          style="width: 100%"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>

      <!-- 标题 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="addForm.title" placeholder="请输入标题" />
      </el-form-item>

             <!-- 富文本信息 -->
       <el-form-item label="信息" prop="message">
         <quill-editor
           v-model="addForm.message"
           ref="myTextEditorAdd"
           :options="editorOption"
           style="height: 350px"
           @change="onEditorChangeAdd"
           @blur="onEditorBlurAdd"
         />
       </el-form-item>
    </el-form>
  </div>

  <span slot="footer" class="dialog-footer">
    <el-button @click="cancelAdd">取 消</el-button>
    <el-button type="primary" @click="saveAdd">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'
import dayjs from 'dayjs';
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import Quill from 'quill'

// 图片调整大小模块
class ImageResize {
  constructor(quill, options) {
    this.quill = quill;
    this.options = options;
    this.init();
  }

  init() {
    this.quill.root.addEventListener('click', (e) => {
      if (e.target && e.target.tagName === 'IMG') {
        const img = e.target;
        const resizeHandles = document.querySelectorAll('.image-resize-handle');
        resizeHandles.forEach(handle => handle.remove());
        
        // 创建调整大小的控制点
        const resizeHandle = document.createElement('div');
        resizeHandle.className = 'image-resize-handle';
        resizeHandle.innerHTML = `
          <div class="image-resize-controls">
            <button class="resize-btn small" title="小尺寸">小</button>
            <button class="resize-btn medium" title="中尺寸">中</button>
            <button class="resize-btn large" title="大尺寸">大</button>
            <button class="resize-btn original" title="原始尺寸">原</button>
          </div>
        `;
        
        // 定位控制面板
        const imgRect = img.getBoundingClientRect();
        const editorRect = this.quill.root.getBoundingClientRect();
        resizeHandle.style.position = 'absolute';
        resizeHandle.style.top = (imgRect.top - editorRect.top + imgRect.height + 5) + 'px';
        resizeHandle.style.left = (imgRect.left - editorRect.left) + 'px';
        resizeHandle.style.zIndex = '1000';
        
        this.quill.root.appendChild(resizeHandle);
        
        // 添加按钮事件监听
        resizeHandle.querySelector('.small').onclick = () => {
          img.style.width = '200px';
          img.style.height = 'auto';
          resizeHandle.remove();
        };
        
        resizeHandle.querySelector('.medium').onclick = () => {
          img.style.width = '400px';
          img.style.height = 'auto';
          resizeHandle.remove();
        };
        
        resizeHandle.querySelector('.large').onclick = () => {
          img.style.width = '600px';
          img.style.height = 'auto';
          resizeHandle.remove();
        };
        
        resizeHandle.querySelector('.original').onclick = () => {
          img.style.width = '';
          img.style.height = '';
          resizeHandle.remove();
        };
        
        // 点击其他地方时隐藏控制面板
        document.addEventListener('click', function hideControls(e) {
          if (!resizeHandle.contains(e.target) && e.target !== img) {
            resizeHandle.remove();
            document.removeEventListener('click', hideControls);
          }
        });
      }
    });
  }
}

// 注册自定义模块
Quill.register('modules/imageResize', ImageResize);

export default {
    components: {
      quillEditor
    },
    name: 'basetable',
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        imgUrl: '',
        query: {
          selected: [],
          conferenceId: null, 
          typeId: null,
          message: '',
          title: '',         
          pageIndex: 1,
          pageSize: 30
        },
        cascaderOptions: [],
        cascaderProps: {
          value: 'id',
          label: 'label',
          children: 'children',
          expandTrigger: 'hover',
        },
        cascaderPropsMultiple: {
          value: 'id',
          label: 'label',
          children: 'children',
          expandTrigger: 'hover',
          multiple: true,
        },
        tableData: [],
        multipleSelection: [],
        exportData: [],
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {
          notificationId: '',
          title: '',
          message: '',
          cascader: [], // 用于级联选择器 v-model，格式：[conferenceId, typeId]
          targetConferenceId: null, // 单独存储
          targetTypeId: null,
          sentAt: ''
        },
        conferences:{},
        users:{},
        vehicles:{},
        addForm: {
          title: '',
          message: '',
          cascader: [], // 级联选择器选中值，支持多选，格式为 [[conferenceId, typeId], [conferenceId, typeId], ...]
          targetConferenceId: null,
          targetTypeId: null,
          selectedTargets: [], // 存储所有选中的会议和用户类型组合
          sentAt: ''
        },
        idx: -1,
        id: -1,
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' }
          ],
          message: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!value || value.trim() === '') {
                  callback(new Error('请输入通知内容'))
                  return
                }
                
                // 移除HTML标签后检查是否有文字内容
                const textContent = value.replace(/<[^>]+>/g, '').trim()
                
                // 检查是否有图片
                const hasImages = /<img[^>]*>/i.test(value)
                
                // 如果既没有文字也没有图片，则验证失败
                if (!textContent && !hasImages) {
                  callback(new Error('请输入通知内容或插入图片'))
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ],
          cascader: [
            { type: 'array', required: true, message: '请选择会议与用户类型', trigger: 'change' }
          ],
          sentAt: [
            { required: true, message: '请选择发送时间', trigger: 'change' }
          ]
        },
                 editorOption: {
           placeholder: '请输入通知内容',
           theme: 'snow',
           modules: {
             toolbar: {
               container: [
                 // 标题与字体大小
                 [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                 [{ 'font': [] }, { 'size': ['small', false, 'large', 'huge'] }],
             
                 // 文本样式
                 ['bold', 'italic', 'underline', 'strike'], // 粗体、斜体、下划线、删除线
             
                 // 上标下标
                 [{ 'script': 'sub' }, { 'script': 'super' }],
             
                 // 文本颜色和背景色
                 [{ 'color': [] }, { 'background': [] }],
             
                 // 对齐方式
                 [{ 'align': [] }],
             
                 // 缩进、列表
                 [{ 'indent': '-1' }, { 'indent': '+1' }],
                 [{ 'list': 'ordered' }, { 'list': 'bullet' }],
             
                 // 引用块、代码块
                 ['blockquote', 'code-block'],
                 
                 // 图片上传
                 ['image'],
             
                 // 清除格式
                 ['clean']
               ],
               handlers: {
                 image: this.imageHandler
               }
             },
             // 启用图片调整大小模块
             imageResize: {}
           }
         }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/notifications/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          message: this.query.message,
          title: this.query.title,
          conferenceId: this.query.conferenceId,
          typeId: this.query.typeId,
        }).then(res=>{
          this.pageTotal = res.total,
          this.tableData = res.data
        });
        requests.get("/notifications/conferences-with-types").then(res=>{
          this.cascaderOptions = res
        })
      },
      //多级选择框
      onCascaderChange(val) {
        if (val.length === 2) {
          this.query.conferenceId = val[0];
          this.query.typeId = val[1];
        } else {
          this.query.conferenceId = null;
          this.query.typeId = null;
        }
      },
      handleCascaderChange(value) {
        if (value && value.length === 2) {
          this.form.targetConferenceId = value[0];
          this.form.targetTypeId = value[1];
        } else {
          this.form.targetConferenceId = null;
          this.form.targetTypeId = null;
        }
      },
      handleCascaderChangeAdd(value){
        // 清空之前的选择
        this.addForm.selectedTargets = [];
        
        if (value && value.length > 0) {
          // 处理多选情况
          value.forEach(selection => {
            if (selection && selection.length === 2) {
              this.addForm.selectedTargets.push({
                conferenceId: selection[0],
                typeId: selection[1]
              });
            }
          });
          
          // 为了兼容图片上传，设置第一个选择的会议ID
          if (this.addForm.selectedTargets.length > 0) {
            this.addForm.targetConferenceId = this.addForm.selectedTargets[0].conferenceId;
            this.addForm.targetTypeId = this.addForm.selectedTargets[0].typeId;
          }
        } else {
          this.addForm.targetConferenceId = null;
          this.addForm.targetTypeId = null;
        }
      },
      //富文本
      onEditorBlur() {
        // 延迟验证，确保内容已更新
        this.$nextTick(() => {
          // 验证并清除符合要求的警告
          this.$refs.formRef.validateField('message')
        })
      },
      
      // 新增模式富文本失焦验证
      onEditorBlurAdd() {
        // 延迟验证，确保内容已更新
        this.$nextTick(() => {
          // 验证并清除符合要求的警告
          this.$refs.formRef.validateField('message')
        })
      },
      
      // 编辑器内容变化时验证（编辑模式）
      onEditorChange() {
        // 如果内容符合要求，立即清除警告
        this.$nextTick(() => {
          if (this.isValidContent(this.form.message)) {
            this.$refs.formRef.clearValidate(['message'])
          }
        })
      },
      
      // 编辑器内容变化时验证（新增模式）
      onEditorChangeAdd() {
        // 如果内容符合要求，立即清除警告
        this.$nextTick(() => {
          if (this.isValidContent(this.addForm.message)) {
            this.$refs.formRef.clearValidate(['message'])
          }
        })
      },
      
      // 检查内容是否有效
      isValidContent(value) {
        if (!value || value.trim() === '') {
          return false
        }
        
        // 移除HTML标签后检查是否有文字内容
        const textContent = value.replace(/<[^>]+>/g, '').trim()
        
        // 检查是否有图片
        const hasImages = /<img[^>]*>/i.test(value)
        
        // 有文字内容或有图片就是有效的
        return textContent.length > 0 || hasImages
      },
      
      // 清理富文本内容中的光标元素和其他不需要的元素
      cleanHtmlContent(htmlContent) {
        if (!htmlContent) return htmlContent;
        
        // 移除 ql-cursor 元素
        let cleanContent = htmlContent.replace(/<span class="ql-cursor">[\s\S]*?<\/span>/g, '');
        
        // 移除空的 span 标签（只包含光标的span）
        cleanContent = cleanContent.replace(/<span[^>]*>\s*<\/span>/g, '');
        
        // 移除多余的空段落
        cleanContent = cleanContent.replace(/<p><\/p>/g, '');
        
        // 移除字符串开头和结尾的空白字符
        cleanContent = cleanContent.trim();
        
        return cleanContent;
      },
      // 触发搜索按钮
      handleSearch() {
          this.query.pageIndex = 1;
          this.loading();
      },
      //时间格式化
      formatDateTime(row, column, cellValue) {
        if (!cellValue) return '';
        const date = new Date(cellValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${date.getFullYear()}/${pad(date.getMonth() + 1)}/${pad(date.getDate())} ` +
               `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      },
      // 删除操作
      handleDelete(row) {
        // 二次确认删除
        this.$confirm('确定要删除吗？', '提示', {
            type: 'warning'
        })
            .then(() => {
                requests.delete("/notifications/delById",{
                  notificationId: row
                }).then(res=>{
                  this.$message.success(res);
                  this.loading()
                })
            })
      },
      // 编辑操作
      handleEdit(row) {
        // 安全深拷贝 row 对象，避免响应式污染
        this.form = {
          notificationId: row.notificationId,
          title: row.title,
          message: row.message,
          sentAt: row.sentAt,
          targetConferenceId: row.targetConferenceId,
          targetTypeId: row.targetTypeId,
          cascader: [row.targetConferenceId, row.targetTypeId]
        };
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        this.$refs.formRef.resetFields()
        // 重置表单（如果需要）
        // this.$refs.form.resetFields();
      },
      // 保存编辑
      saveEdit() {
        // 先校验表单
        this.$refs.formRef.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
          
          // 清理富文本内容中的光标元素
          const cleanForm = {
            ...this.form,
            message: this.cleanHtmlContent(this.form.message)
          };
          
          // 校验成功，调用接口
          requests.post("/notifications/edit", cleanForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              this.editVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
            })
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 单选、多选改变时调用
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的酒店');
          return;
        }
      
        this.$confirm(`确定删除这 ${this.multipleSelection.length} 项吗？`, '提示', {
          type: 'warning'
        })
          .then(() => {
            const ids = this.multipleSelection.map(item => item.notificationId);
            requests.post('/notifications/delByIds', ids)  // ✅ 注意这里直接传数组
              .then(res => {
                this.$message.success(res);
                this.loading(); // 重新加载表格
              })
          })
      },
      //新增操作
      handleAdd() {
        this.addVisible = true;
      },
      // 取消操作
      cancelAdd() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
        // 重置表单（如果需要）
        this.$refs.addFormRef.resetFields();
      },
      // 保存操作
      saveAdd() {
        // 先校验表单
        this.$refs.formRef.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            this.$message.error('请检查表单内容是否完整');
            return;
          }
          
          // 额外检查富文本内容（双重保险）
          if (!this.isValidContent(this.addForm.message)) {
            this.$message.error('请输入通知内容或插入图片');
            return;
          }
          
          // 检查是否有选择目标
          if (!this.addForm.selectedTargets || this.addForm.selectedTargets.length === 0) {
            this.$message.warning('请至少选择一个会议和用户类型');
            return;
          }
          
          // 清理富文本内容
          const cleanMessage = this.cleanHtmlContent(this.addForm.message);
          
          // 显示批量发送提示
          const loadingMessage = this.$message({
            message: `正在发送通知到 ${this.addForm.selectedTargets.length} 个目标...`,
            type: 'info',
            duration: 0
          });
          
          // 批量发送请求
          const promises = this.addForm.selectedTargets.map(target => {
            const requestData = {
              title: this.addForm.title,
              message: cleanMessage,
              targetConferenceId: target.conferenceId,
              targetTypeId: target.typeId,
              sentAt: this.addForm.sentAt
            };
            
            return requests.post("/notifications/add", requestData);
          });
          
          // 等待所有请求完成
          Promise.all(promises)
            .then(responses => {
              loadingMessage.close();
              this.$message.success(`成功发送通知到 ${responses.length} 个目标`);
              this.addVisible = false;    // 请求成功后关闭弹窗
              this.loading();              // 刷新数据
              
              // 重置表单
              this.resetAddForm();
            })
            .catch(error => {
              loadingMessage.close();
              this.$message.error('部分通知发送失败，请检查后重试');
            });
        });
      },
      
      // 重置新增表单
      resetAddForm() {
        this.addForm = {
          title: '',
          message: '',
          cascader: [],
          targetConferenceId: null,
          targetTypeId: null,
          selectedTargets: [],
          sentAt: ''
        };
      },
      
      // 获取目标的显示名称
      getTargetDisplayName(target) {
        // 在级联选择器选项中查找对应的显示名称
        const conference = this.cascaderOptions.find(conf => conf.id === target.conferenceId);
        if (!conference) return '未知会议';
        
        const userType = conference.children.find(type => type.id === target.typeId);
        if (!userType) return conference.label + ' - 未知类型';
        
        return `${conference.label} - ${userType.label}`;
      },
             // 图片上传至阿里云 OSS
       uploadToOSS(file, callback) {
         // 获取当前选中的会议ID
         let conferenceId = null;
         if (this.editVisible && this.form.targetConferenceId) {
           conferenceId = this.form.targetConferenceId;
         } else if (this.addVisible && this.addForm.targetConferenceId) {
           conferenceId = this.addForm.targetConferenceId;
         }
         
         // 如果没有选中会议，提示用户先选择会议
         if (!conferenceId) {
           this.$message.warning('请先选择会议后再上传图片');
           return;
         }
         
         // 获取签名
         requests.get('/files/policy', {
           conferenceId: conferenceId
         }).then(res => {
          
          const data = res;
          const fileName = Date.now() + '-' + file.name;
          const key = data.dir + fileName;
          
          const formData = new FormData();
          formData.append('key', key);
          formData.append('policy', data.policy);
          formData.append('OSSAccessKeyId', data.accessid);
          formData.append('success_action_status', '200');
          formData.append('signature', data.signature);
          formData.append('file', file);
          
          // 上传到阿里云
          requests.post(data.host, formData).then(() => {
            const url = `${data.host}/${key}`;
            this.imgUrl = url;
            
            // 调用回调函数，将图片URL传递给Quill编辑器
            if (callback) {
              callback(url);
            }
            
            this.$message.success('图片上传成功');
          }).catch(error => {
            this.$message.error('图片上传失败');
          });
        }).catch(error => {
          this.$message.error('获取上传签名失败');
        });
      },
      // 自定义图片处理器
      imageHandler() {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();
        
        input.onchange = () => {
          const file = input.files[0];
          if (file) {
            // 检查文件类型
            if (!file.type.startsWith('image/')) {
              this.$message.error('请选择图片文件');
              return;
            }
            
            // 检查文件大小 (例如限制为5MB)
            if (file.size > 5 * 1024 * 1024) {
              this.$message.error('图片大小不能超过5MB');
              return;
            }
            
            // 显示上传中状态
            const loadingMessage = this.$message({
              message: '图片上传中...',
              type: 'info',
              duration: 0
            });
            
            // 上传图片
            this.uploadToOSS(file, (imageUrl) => {
              // 关闭loading消息
              loadingMessage.close();
              
              // 判断当前活跃的编辑器
              let quill;
              if (this.editVisible && this.$refs.myTextEditor) {
                quill = this.$refs.myTextEditor.quill;
              } else if (this.addVisible && this.$refs.myTextEditorAdd) {
                quill = this.$refs.myTextEditorAdd.quill;
              }
              
              if (quill) {
                // 获取当前光标位置
                const range = quill.getSelection();
                const index = range ? range.index : quill.getLength();
                
                // 插入图片到编辑器
                quill.insertEmbed(index, 'image', imageUrl);
                
                // 将光标移动到图片后面
                quill.setSelection(index + 1);
              }
            });
          }
        };
      },
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
/* 对话框样式调整 */
.notification-dialog .el-dialog {
  min-height: 85vh;      /* 设置最小高度为视窗高度的85% */
  max-height: 95vh;      /* 设置最大高度为视窗高度的95% */
  margin-top: 2.5vh !important;  /* 调整顶部间距 */
  margin-bottom: 2.5vh !important;  /* 调整底部间距 */
}

.notification-dialog .el-dialog__body {
  padding: 20px 25px;    /* 增加对话框内容区域的内边距 */
  max-height: calc(95vh - 120px);  /* 计算内容区域最大高度 */
  overflow-y: auto;      /* 内容超出时显示滚动条 */
}

.notification-dialog .el-dialog__header {
  padding: 20px 25px 15px;  /* 调整头部内边距 */
}

.notification-dialog .el-dialog__footer {
  padding: 15px 25px 20px;  /* 调整底部内边距 */
}

.dialog-scroll-body {
  max-height: calc(95vh - 200px);  /* 调整滚动容器最大高度 */
  overflow-y: auto;      /* 超出自动滚动 */
  padding-right: 10px;   /* 防止滚动条压住内容 */
}

/* 表单项间距调整 */
.notification-dialog .el-form-item {
  margin-bottom: 20px;   /* 增加表单项之间的间距 */
}

/* 富文本编辑器容器调整 */
.notification-dialog .el-form-item .quill-editor {
  margin-bottom: 10px;   /* 富文本编辑器底部间距 */
}

/* 已选择目标显示样式 */
.selected-targets {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  min-height: 50px;
}

.selected-targets .target-count {
  margin-top: 8px;
  color: #666;
  font-size: 12px;
}

/* 图片调整大小控制面板样式 */
.image-resize-handle {
  position: absolute;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 5px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

.image-resize-controls {
  display: flex;
  gap: 5px;
}

.resize-btn {
  padding: 4px 8px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.resize-btn:hover {
  background: #f5f5f5;
  border-color: #409eff;
  color: #409eff;
}

.resize-btn:active {
  background: #409eff;
  color: white;
}

/* 图片选中时的样式 */
.ql-editor img:hover {
  cursor: pointer;
  box-shadow: 0 0 0 2px #409eff;
  border-radius: 4px;
}
</style>
